package com.martian.common.util;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.ArrayList;

/**
 * @author martian
 * @version V1.0.0
 * @Description
 * @date 2023-03-25 21:28
 */
@Data
@AllArgsConstructor
public class Embedding {
    private ArrayList<Float> embedVector;

    public Embedding() {
    }

    public static ArrayList<Float> parseStrToEmbArray(String StringEmb){
        String[] EmbVectors = StringEmb.split(" ");
        ArrayList<Float> FloatEmb = new ArrayList<>();
        for (String vector : EmbVectors) {
//            System.out.println(vector);
            FloatEmb.add(Float.parseFloat(vector));
        }
        return  FloatEmb;
    }
    public double calculateSimilarity(Embedding otherEmb){
        if (null == embedVector || null == otherEmb || null == otherEmb.getEmbedVector()
                || embedVector.size() != otherEmb.getEmbedVector().size()){
            return -1;
        }
        double dotProduct = 0;
        double denominator1 = 0;
        double denominator2 = 0;
        //这里采用余弦相似度计算 @TODO 其更多从方向上区分差异，对绝对数值差异不敏感，改进是进行归一化
        for (int i = 0; i < embedVector.size(); i++){
            dotProduct += embedVector.get(i) * otherEmb.getEmbedVector().get(i);
            denominator1 += embedVector.get(i) * embedVector.get(i);
            denominator2 += otherEmb.getEmbedVector().get(i) * otherEmb.getEmbedVector().get(i);
        }
        return dotProduct / (Math.sqrt(denominator1) * Math.sqrt(denominator2));
    }
}
